<template>
	<view class="page-container">
		<u-picker :show="show" :columns="columns" keyName="admdivName" :defaultIndex=[3] @cancel='show=false'
			@confirm="handleProvinceChange">
		</u-picker>
		<u-datetime-picker :show="showMonth" mode="year-month" @cancel='showMonth=false' v-model="dateVal"
			@confirm="handleMonthChange">
		</u-datetime-picker>
		<view class="main-content">
			<view class="query-box">

				<view class="query-content">
					<view class="form-grid">
						<!-- 省份选择 -->
						<view class="form-item">
							<view class="form-label">归集省份:</view>
							<view class="province-select" @click="show=true">
								<view>
									{{selectedProvince.admdivName}}
								</view>
								<u-icon name="arrow-down" size="16"></u-icon>
							</view>
						</view>

						<!-- 报销月份 -->
						<view class="form-item">
							<view class="form-label">归集月份:</view>
							<view class="province-select" @click="showMonth=true">
								<view>
									{{selectedMonth}}
								</view>
								<u-icon name="arrow-down" size="16"></u-icon>
							</view>
						</view>
						<!-- 报销月份 -->
						<view class="form-item">
							<view class="form-label">归集方式:</view>
							<u-radio-group v-model="collectType">
								<u-radio :customStyle="{margin: '16px'}" v-for="(item, index) in formatList"
									:key="item.value" :label="item.name" :name="item.value">
								</u-radio>
							</u-radio-group>
						</view>
					</view>
					<!-- 按钮区域 -->
					<view class="btn-group">
						<u-button text="开始归集" type="primary" size="small" class="query-btn"
							@click="handleQuery"></u-button>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script>
	import {
		saveEinvoiceCollect
	} from '@/api/homeApi.js'
	export default {
		data() {
			return {
				showMonth: false,
				dateVal: Number(new Date()),
				selectedMonth: '',
				collectType: 1,
				formatList: [{
					name: '身份证号',
					value: 1
				}, {
					name: '姓名+身份证号',
					value: 2
				}],
				show: false,
				// 省份列表
				columns: [], //格式为[[]]
				selectedProvince: {
					admdivName: '河北省',
					admdivCode: '130000'
				},
			}
		},
		created() {
			this.conversionDate()
		},
		methods: {
			// 省份变化处理
			handleProvinceChange(e) {
				this.show = false
				console.log('===', e)
				this.selectedProvince = e.value[0]
			},
			handleMonthChange(e) {
				this.showMonth = false;
				// e.value 是时间戳
				const date = new Date(e.value);
				// 格式化为 "YYYY年MM月"
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				this.selectedMonth = `${year}-${month < 10 ? '0' + month : month}`;
				console.log('选择的月份:', this.selectedMonth);
			},
			async handleQuery() {
				try {
					uni.showLoading({
						title: '自动归集中'
					})
					const [year, month] = this.selectedMonth.split('-')
					const startDate = year + month + '01'
					const lastDate = year + month + this.getLastDay(this.selectedMonth)
					const res = await saveEinvoiceCollect({
						areaCode: this.selectedProvince.admdivCode.substring(0, 2),
						bgnDate: startDate,
						endDate: lastDate,
						collectType: this.collectType
					})
					if (res.result == 0) {
						uni.hideLoading()
						this.$u.toast('归集成功，请去票夹查看');
					} else {
						uni.hideLoading()
						this.$u.toast(res.message || '接口错误');
					}
				} catch (error) {
					uni.hideLoading()
					this.$u.toast(error.message || '接口错误');
					//TODO handle the exception
				}
			},
			async conversionDate() {
				const date = new Date();
				// 格式化为 "YYYY年MM月"
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const nowDate = `${year}-${month < 10 ? '0' + month : month}`;
				console.log('===', nowDate)
				this.selectedMonth = nowDate
			},
			getLastDay(date) {
				// 输入的年月字符串
				const yearMonth = date;
				// 分割成年和月（注意月份在 JS 中是 0 开始的，需要减 1）
				const [year, month] = yearMonth.split('-').map(Number);
				// 构造下一个月的第一天（例如 2025-02 的下一个月第一天是 2025-03-01）
				const nextMonthFirstDay = new Date(year, month, 1);
				// 减去 1 天，得到当前月的最后一天
				const lastDay = new Date(nextMonthFirstDay - 24 * 60 * 60 * 1000);
				// 格式化结果（获取日期部分）
				const lastDate = lastDay.getDate(); // 例如 2025-02 的最后一天是 28，结果为 28
				return lastDate
			},
		}
	}
</script>

<style>
	.page-container {
		font-size: 28rpx;
		color: #1D2129;
	}

	.province-select {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 80%;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		height: 40rpx;
		padding: 10rpx;
		font-size: 14px;
		/* 120px -> 180rpx */
	}

	.query-box {
		background-color: #fff;
		border-radius: 16rpx;
		box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
		padding: 20rpx;
		margin-bottom: 20rpx;
		transition: height 0.3s ease;
	}

	.main-content {
		padding: 30rpx 24rpx;
	}

	.query-content {
		padding-top: 10rpx;
	}

	.form-grid {
		display: grid;
		grid-template-columns: 1fr;
		gap: 24rpx;
	}

	@media (min-width: 768px) {
		.form-grid {
			grid-template-columns: repeat(3, 1fr);
		}
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.form-label {
		width: 120rpx;
		font-size: 26rpx;
		color: #4E5969;
	}

	.form-control {
		flex: 1;
		height: 40rpx;
		border-radius: 8rpx;
		font-size: 14px;
	}

	.navigator-wrap {
		flex: 1;
	}

	.btn-group {
		display: flex;
		justify-content: center;
		gap: 20rpx;
		padding-top: 20rpx;
	}

	.query-btn {
		width: 160rpx;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #165DFF;
	}

	.reset-btn {
		width: 160rpx;
		height: 60rpx;
		line-height: 60rpx;
		background-color: #F2F3F5;
		color: #4E5969;
	}
</style>